<template>
  <div class="create-post-page">
    <h4>{{ isEditMode ? '编辑文章' : '新建文章' }}</h4>
    <UploaderFile
      action="/upload"
      class="d-flex align-items-center justify-content-center bg-light text-secondary w-100 my-4"
      :beforeUpload="uploadedCheck"
      @file-uploade="handleFileUploaded"
      :uploaded="uploadeData"
    >
      <h2>上传头图</h2>
      <template #loading>
        <div class="d-flex">
          <div class="spinner-border text-secondary" roule="status">
            <!-- <span class="scr-only"></span> -->
          </div>
        </div>
        <h2>正在上传</h2>
      </template>
      <template #uploaded="dataProps">
        <div class="uploaded-area">
          <img :src="dataProps.uploadedData.data.url" />
          <h3>重新上传</h3>
        </div>
      </template>
    </UploaderFile>
    <!-- <input type="file" name="file" @change.prevent="handleFileChange" /> -->
    <ValidateForm @form-submit="onFormSubmit">
      <div class="mb-3">
        <label for="" class="form-label">文章标题：</label>
        <ValidateInput
          placeholder="请输入文章标题"
          type="text"
          :rules="titleRules"
          v-model="titleVal"
        ></ValidateInput>
      </div>
      <div class="mb-3">
        <label for="" class="form-label">文章详情：</label>
        <textarea ref="textArea"></textarea>
        <ValidateInput
          placeholder="请输入文章详情"
          rows="10"
          tag="textarea"
          type="text"
          :rules="contentRules"
          v-model="contenVal"
          @value="contentValue"
        ></ValidateInput>
      </div>
      <template #submit>
        <button class="btn btn-primary btn-large">
          {{ isEditMode ? '更新文章' : '发表文章' }}
        </button>
      </template>
    </ValidateForm>
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, ref } from 'vue'
import { useStore } from 'vuex'
import {
  GolbalDataProps,
  UserProps,
  ResponseType,
  ImageProps,
  PostProps
} from '../store'
import { useRoute, useRouter } from 'vue-router'
import ValidateForm from './ValidateForm.vue'
import ValidateInput, { RulesProp } from './ValidateInput.vue'
import UploaderFile from './UploaderFile.vue'
import { beforeUploadCheck } from '../hook/helper'
import createMessage from '../hook/createMessage'
import axios from 'axios'
import { file } from '@babel/types'
import EasyMDE from 'easymde'



export default defineComponent({
  name: 'CreatePost',
  components: {
    ValidateForm,
    ValidateInput,
    UploaderFile
  },
  setup () {
    const textArea = ref<null | HTMLTextAreaElement>(null)
    const titleVal = ref('')
    const titleValue = (val: string) => {
      titleVal.value = val
    }
    const router = useRouter()
    const route = useRoute()
    const isEditMode = !!route.query.id
    const uploadeData = ref()
    const store = useStore<GolbalDataProps>()
    const titleRules: RulesProp = [
      { type: 'required', message: '文章标题不能为空' }
    ]
    const contenVal = ref('')
    const contentValue = (val: string) => {
      contenVal.value = val
    }
    const contentRules: RulesProp = [
      {
        type: 'required',
        message: '文章详情不能为空'
      }
    ]
    const uploadedCheck = (file: File) => {
      const result = beforeUploadCheck(file, {
        format: ['image/jpeg', 'image/png'],
        size: 1
      })
      const { passed, error } = result
      // 根据不同的类型返回不同的信息
      if (error === 'format') {
        createMessage('上传图片只能是JPG/PNG格式', 'error')
      }
      if (error === 'size') {
        createMessage('上传图片大小不能超过1MB', 'error')
      }
      return passed
    }
    let imageId = ''
    const handleFileUploaded = (rawData: ResponseType<ImageProps>) => {
      if (rawData.data._id) {
        imageId = rawData.data._id
        console.log(imageId)
      }
    }
    onMounted(() => {
      if (textArea.value) {
        const easyMDEInstance = new EasyMDE({ element: textArea.value})
      }
      // 如果是编辑文章
      if (isEditMode) {
        // rawdata 请求回来的值
        store
          .dispatch('fetchPost', route.query.id)
          .then((rawData: ResponseType<PostProps>) => {
            const currentPost = rawData.data
            // 如果存在就赋值
            if (currentPost.image) {
              // 头图
              uploadeData.value = { data: currentPost.image }
            }
            titleVal.value = currentPost.title
            contenVal.value = currentPost.content || ''
          })
      }
    })
    const onFormSubmit = (result: boolean) => {
      if (result) {
        const { column, _id } = store.state.user
        if (column) {
          const newPost: PostProps = {
            // id: new Date().getTime(),
            // _id: '',
            title: titleVal.value,
            content: contenVal.value,
            column,
            // createdAt: new Date().toLocaleString(),
            author: _id
          }
          if (imageId) {
            newPost.image = imageId
          }
          const actionName = isEditMode ? 'updatePost' : 'createPost'
          const sendData = isEditMode
          ? {
            id:route.query.id,
            payload:newPost
          }
          : newPost
          store.dispatch(actionName, sendData).then(() => {
            createMessage('发表成功，2秒后跳转文章', 'success')
            setTimeout(() => {
              router.push({ name: 'column', params: { id: column } })
            }, 2000)
          })

          // 自动跳转到详情页
          // store.commit('createPost', newPost)
          // router.push({ name: 'column', params: { id: columnId } })
        }
      }
    }
    // 控制文件上传变化的
    const handleFileChange = (e: Event) => {
      console.log(e)
      // 在这个input组件中，我们可以拿到它选择的 file对象，也就是文件对象
      const target = e.target as HTMLInputElement // 断言成一个input框元素
      const files = target.files
      // 这是一个files列表，也就是fileList对象
      // 它是一个array-link的object的一个伪数组的对象，但不是一个数组，支持选择多个文件
      // 判断里面是否有值
      if (files) {
        // 我们拿到它的第一项，就是我们选择的文件
        const upoladeFile = files[0]
        // 我们来模拟表单的数据，我们可以使用FormData对象，这是另一种针对XHR2设计的新数据类型
        // 使用fromData能够很方便实现 javaScript 创建 HTML
        // 表单数据串联化就是name=zs&age=13的这种方式
        const formData = new FormData()
        // 通过append方法其附加了<input>
        // 我们通过 FormData 对象添加了input的值
        formData.append(upoladeFile.name, upoladeFile)
        axios
          .post('/upload', formData, {
            headers: {
              // 设置请求头
              'Content-Type': 'multipart/form-data'
            }
          })
          .then((resp) => {
            console.log(resp)
          })
      }
    }
    return {
      titleVal,
      titleRules,
      contenVal,
      contentRules,
      onFormSubmit,
      // titleValue,
      contentValue,
      uploadedCheck,
      handleFileUploaded,
      isEditMode,
      uploadeData,
      textArea
     
    }
  }
})
</script>

<style>
.create-post-page .file-upload-container {
  height: 200px;
  cursor: pointer;
  overflow: hidden;
}
.create-post-page .file-upload-container img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
</style>
